<template>
  <div class="delivery_create">
    <Row class="delivery_create_info">
      <Form inline
            ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="120"
            v-if="type===1"
            style="width: 850px;">
        <div class="title"><span></span>基本信息</div>
        <FormItem prop="shopId"
                  label="选择门店：">
          <treeselect :options="options"
                      @select="selectListd"
                      class='input-wid'
                      :clearable="clearable"
                      :disable-branch-nodes="true"
                      style='width:260px'
                      :disabled="disabled"
                      :normalizer="normalizer"
                      noResultsText="未搜索符合的门店"
                      noOptionsText="门店为空"
                      placeholder="请选择门店"
                      v-model='formValidate.shopId' />
        </FormItem>
        <FormItem prop="machinePosition"
                  :label-width="180"
                  label="机台位置：">
          <Select v-model="formValidate.machinePosition"
                  style="width:260px"
                  :disabled="disabled"
                  placeholder='请选择'>
            <Option v-for="item in machinePositionList"
                    :value="item.id"
                    :key="item.id">{{ item.value }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="shippingType"
                  label="发货类型：">
          <Select v-model="formValidate.shippingType"
                  style="width:260px"
                  :disabled="disabled"
                  placeholder='请选择'>
            <Option v-for="item in typeList"
                    :value="item.id"
                    :key="item.id">{{ item.value }}</Option>
          </Select>
        </FormItem>
        <!-- <FormItem prop="abbreName"
                  label="供应商名称/VN："
                  :label-width="180">
          <sass-select v-model="formValidate.abbreName"
                       @on-change="handleCodeChange2"
                       :loading="loading2"
                       remote
                       label-in-value
                       :remote-method="handleRemoteMethod2"
                       transfer
                       filterable
                       placeholder="请输入搜索"
                       style="width:260px"
                       class="input-width">
            <Option v-for="(item, index) in pnCodeData2"
                    :value="item.suppNameShorten"
                    :label="item.suppName"
                    :key="index">{{ item.suppName }}</Option>
          </sass-select> -->
        <!-- <Select v-model="formValidate.supplyId"
                  @on-change="handleCodeChange"
                  :disabled="disabled"
                  :loading="loading2"
                  remote
                  style="width:260px"
                  label-in-value
                  :remote-method="handleRemoteMethod2"
                  transfer
                  filterable
                  placeholder="请输入搜索"
                  class="input-width">
            <Option v-for="(item, index) in pnCodeData2"
                    :value="item.machineSupplierId"
                    :label="item.supplierName"
                    :key="index">{{ item.supplierName }}</Option> -->
        <!-- </Select>
        </FormItem> -->
        <FormItem prop="pnCode"
                  label="机台产品/PN："
                  :label-width="180">
          <Select v-model="formValidate.pnCode"
                  :loading="loading"
                  :disabled="disabled"
                  @on-change="handleCodeChange"
                  ref="pnCodeSetect"
                  remote
                  :remote-method="handleRemoteMethod"
                  transfer
                  style="width:260px"
                  filterable
                  placeholder="请选择"
                  class="input-width">
            <Option v-for="(item, index) in pnCodeData"
                    :value="item.pnCode"
                    :key="index">{{
              item.pnCode
              }}</Option>
          </Select>

        </FormItem>
        <FormItem prop="shippedQuantity"
                  label="发货数量：">
          <Select v-model="formValidate.shippedQuantity"
                  transfer
                  :disabled="disabled"
                  placeholder="请选择"
                  style="width:260px"
                  class="input-width">
            <Option v-for="item in purchaseAmountData"
                    :value="item.value"
                    :key="item.value">{{
              item.label
              }}</Option>
          </Select>
        </FormItem>
        <div class="title"><span></span>财务信息</div>
        <FormItem prop="taxPrice"
                  label="含税单价：">
          <Input v-model="formValidate.taxPrice"
                 style="width:260px"
                 @on-keyup="taxkeyup"
                 :disabled="disabled"
                 placeholder="请输入小数点前7位及后6位" />
        </FormItem>
        <FormItem prop="taxRate"
                  label="税率："
                  :label-width="180">
          <!-- <Input v-model="formValidate.taxRate"
                 style="width:260px"
                 placeholder="请输入小数点前7位及后6位" /> -->
          <Select v-model="formValidate.taxRate"
                  style="width:260px"
                  clearable
                  :disabled="disabled"
                  placeholder='请选择'>
            <Option v-for="item in taxRateList"
                    :value="item.id"
                    :key="item.id">{{ item.value }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="settlemenPrice"
                  label="内部结算单价：">
          <Input v-model="formValidate.settlemenPrice"
                 :disabled="disabled"
                 @on-keyup="settlemekeyup"
                 style="width:260px"
                 placeholder="请输入小数点前7位及后6位" />
        </FormItem>
        <Row>
          <FormItem>
            <Button type="primary"
                    class="btn"
                    v-if="!disabled"
                    style="margin-right: 24px;width:100px;"
                    @click="submitForm">确认</Button>
            <Button class="btn"
                    style="width:100px;"
                    @click="reset">取消</Button>
          </FormItem>
        </Row>
      </Form>
    </Row>
  </div>
</template>
<script>
import regExp from '@/libs/regExp'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { machineList, supplierList, invoiceCreate, invoiceGet } from '@/api/asset/repair/asset-manage'
import sassSelect from '@/components/sass-select'
import { getOrgAllTree } from '@/api/system/org'
export default {
  name: 'delivery_create',
  components: { Treeselect, sassSelect },
  data () {
    return {
      clearable: true,
      codeDisabled: false,
      pnCodeData: [],
      pnCodeData2: [],
      purchaseAmountData: [],
      loading: false,
      loading2: false,
      type: 1,
      typeList: [
        { id: '1', value: '新购' },
        { id: '2', value: '合作' },
        { id: '3', value: '试用' }
      ],
      machinePositionList: [
        { id: 0, value: '店内' },
        { id: 1, value: '店外' }
      ],
      taxRateList: [
        { id: 0.13, value: '13%' },
        { id: 0.09, value: '9%' },
        { id: 0.06, value: '6%' }
      ],
      formValidate: {
        merchantId: this.$store.state.user.merchantId,
        shippingType: this.$route.query.type,
        shopId: null,
        pnCode: '',
        supplyId: '',
        // abbreName: '',
        // supplierName: '',
        machinePosition: '',
        shippedQuantity: '',
        taxPrice: '',
        taxRate: '',
        settlemenPrice: '',
        creatorId: this.$store.state.user.userId,
        creatorName: this.$store.state.user.userName,
        consignorName: this.$store.state.user.userName,
        consignorId: this.$store.state.user.userId
      },
      invoiceId: '',
      options: [],
      normalizer (node) {
        return {
          id: node.id,
          label: node.orgName,
          children: node.childList && node.childList.length ? node.childList : undefined
        }
      },
      ruleValidate: {
        shopId: { required: true, message: '请选择门店', trigger: 'blur' },
        machinePosition: { required: true, message: '请选择机台位置', trigger: 'change', type: 'number' },
        shippingType: { required: true, message: '请选择发货类型', trigger: 'change' },
        abbreName: { required: true, message: '请选择供应商名称/VN' },
        pnCode: [{ required: true, message: '请生成PN编码' }],
        shippedQuantity: { required: true, message: '请选择发货数量' },
        taxPrice: [
          // { required: true, message: '请输入含税单价', trigger: 'blur' },
          { message: '请输入小数点前7位及后6位', trigger: 'blur', pattern: regExp.numD6 }
        ],
        // taxRate: { required: true, message: '请选择税率', trigger: 'change', type: 'number' },
        settlemenPrice: [
          { message: '请输入小数点前7位及后6位', trigger: 'blur', pattern: regExp.numD6 }
        ]
      }
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'delivery_create') {
        if (newRoute.query.type) {
          if (newRoute.query.type !== this.formValidate.shippingType) {
            //   // this.disabled = false
            this.invoiceId = ''
            this.formValidate = {
              merchantId: this.$store.state.user.merchantId,
              shippingType: this.$route.query.type,
              shopId: null,
              pnCode: '',
              supplyId: '',
              machinePosition: '',
              // abbreName: '',
              // supplierName: '',
              shippedQuantity: '',
              taxPrice: '',
              taxRate: '',
              settlemenPrice: '',
              creatorId: this.$store.state.user.userId,
              creatorName: this.$store.state.user.userName,
              consignorName: this.$store.state.user.userName,
              consignorId: this.$store.state.user.userId
            }
            this.$refs.formValidate.resetFields()
            this.formValidate.shippingType = newRoute.query.type
          }
        }
        if (newRoute.query.invoiceId) {
          // this.disabled = true
          if (newRoute.query.invoiceId !== this.invoiceId) {
            this.invoiceId = newRoute.query.invoiceId
            this.getDetail()
          }
        }
      }
    },
    'formValidate.pnCode': {
      handler (val) {
        console.log('dd', val)
      },
      deep: true
    }
  },
  computed: {
    disabled () {
      if (this.invoiceId) {
        return true
      } else {
        return false
      }
    }
  },
  mounted () {
    this.purchaseAmountData = Array.from(new Array(999).keys(), x => {
      return { value: x + 1, label: x + 1 }
    })
    this.$refs.pnCodeSetect.$el.getElementsByClassName('ivu-select-input')[0].setAttribute('maxlength', 12)
    this.invoiceId = this.$route.query.invoiceId
    this.formValidate.shippingType = this.$route.query.type
    this.getOrg()
    this.getDetail()
  },
  methods: {
    selectListd (data) {
      this.formValidate.shopId = data.id
    },
    getOrg () {
      getOrgAllTree({
        'merchantId': this.$store.state.user.merchantId,
        'orgType': 1,
        status: 1,
        perms: 'moms:assets:invoiceview'
        // id: this.$store.state.user.orgId
      }).then(res => {
        if (res.data.status === 200) {
          // res.data.data.isDisabled = true
          this.options = [res.data.data]
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    handleRemoteMethod (query) {
      console.log('ss', query)
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          machineList({
            name: query
          }).then(res => {
            if (res.data.status === 200) {
              this.pnCodeData = res.data.data || []
            } else {
              this.$Message.error(res.data.error)
            }
          })
        }, 200)
      } else {
        this.pnCodeData = []
      }
    },
    getDetail () {
      if (this.invoiceId) {
        invoiceGet({
          invoiceId: this.invoiceId
        }).then(res => {
          if (res.data.status === 200) {
            let result = res.data.data || {}
            this.formValidate = result
            this.formValidate.shippingType = result.shippingType.toString()
          } else {
            this.$Message.error(res.data.error)
          }
        })
      }
    },
    handleCodeChange (val) {
      console.log(val)
      // this.formValidate.supplyId = this.pnCodeData
      this.formValidate.supplyId = this.pnCodeData
        .filter(item => item.pnCode === val)
        .map(item => item.machineSupplierId)
        .join()
    },
    taxkeyup () {
      let val = this.formValidate.taxPrice
      val = val.replace(/[^\d.]/g, '')
      val = val.replace(/^\./g, '')
      val = val.replace(/\.{2,}/g, '.')
      val = val.replace('.', '$#$').replace(/\./g, '').replace(
        '$#$', '.')
      this.formValidate.taxPrice = val
    },
    settlemekeyup () {
      let val = this.formValidate.settlemenPrice
      val = val.replace(/[^\d.]/g, '')
      val = val.replace(/^\./g, '')
      val = val.replace(/\.{2,}/g, '.')
      val = val.replace('.', '$#$').replace(/\./g, '').replace(
        '$#$', '.')
      this.formValidate.settlemenPrice = val
    },
    async handleRemoteMethod2 (query) {
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        this.loading2 = true
        const res = await supplierList({ keyword: query, dispFlag: 2, merchantId: this.$store.state.user.merchantId, displayOrder: 1, supplierTypeCode: 2 })
        this.loading2 = false
        if (res.data.status !== 200) return this.$Message.error(res.data.error)
        this.pnCodeData2 = res.data.data || []
      }, 500)
      // console.log(query)
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      // this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      if (this.$store.state.app.tagNavList[this.$store.state.app.tagNavList.length - 1].name !== 'delivery_management') {
        this.$nextTick(() => {
          this.$router.push({
            name: 'delivery_management'
          })
        })
      }
    },
    reset () {
      this.handleReset()
    },
    submitForm () {
      // const { shopId, merchantId, machinePosition, pnCode, supplyId, shippingType, shippedQuantity, taxPrice, taxRate, settlemenPrice } = { ...this.formValidate }
      this.$refs.formValidate.validate((val) => {
        if (val) {
          invoiceCreate({
            ...this.formValidate
          }).then(res => {
            console.log(res)
            if (res.data.status === 200) {
              this.$Message.success('新增成功')
              this.handleReset()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.delivery_create {
  .delivery_create_info {
    width: 800px;
    margin: auto;
  }
  .title {
    font-size: 14px;
    color: #464c5b;
    letter-spacing: 0;
    line-height: 20px;
    margin: 24px 0;
    padding-left: 40px;
    > span {
      display: inline-block;
      width: 8px;
      height: 20px;
      vertical-align: top;
      background: #2d8cf0;
      margin-right: 10px;
    }
  }
}
</style>
